import Core.Test
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements
import java.awt.FlowLayout
import java.awt.GridLayout
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.io.IOException
import java.io.OutputStreamWriter
import java.io.PrintStream
import java.lang.Thread.sleep
import java.net.URL
import java.nio.charset.StandardCharsets
import javax.imageio.ImageIO
import javax.swing.ImageIcon
import javax.swing.JButton
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JPanel
import kotlin.concurrent.thread
import kotlin.system.exitProcess


class SwingControlDemo {
    private lateinit var mainFrame: JFrame
    private lateinit var headerLabel: JLabel
    private lateinit var statusLabel: JLabel
    private lateinit var controlPanel: JPanel


    fun describe(obj: Any): String {
        //  Lambda 表达式
        //   代码块
// 创建一个新的线程
        //init{}
        //   val thread = thread(start = true) {
        // 在这里定义线程要执行的任务
        //          println("This is running on a separate thread.")
        //     }

        // 主线程继续执行其他任务
        //      println("This is running on the main thread.")

        // 等待线程执行完毕
        //    thread.join()

        // 主线程继续执行其他任务
        //   println("Thread execution completed.")


        return when (obj) {
            1 -> "One"
            "Hello" -> "Greeting"
            is Long -> "Long"
            !is String -> "Not a String"
            else -> "Unknown"
        }
    }

    // 定义一个独立的函数，用于获取并显示图片
    private fun fetchAndDisplayImages(frame: JFrame, url: String) {
        try {
            val doc: Document = Jsoup.connect(url).get()
            val imgElements: Elements = doc.select("img")

            // 遍历所有的图片元素
            for (imgElement in imgElements) {
                try {
                    var imgUrl: String = imgElement.attr("src")
                    if (imgUrl.startsWith("//")) {
                        imgUrl = "https:$imgUrl"
                    }

                    // 加载图片并创建 ImageIcon
                    val imageURL = URL(imgUrl)
                    val icon = ImageIcon(ImageIO.read(imageURL))

                    // 创建 JLabel，并将 ImageIcon 设置为其图标
                    val label = JLabel(icon)

                    // 将 JLabel 添加到 JFrame 中
                    frame.add(label)
                } catch (e: Exception) {
                }
                // 获取图片地址

            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun prepareGUI() {


        mainFrame = JFrame("Kotlin SWING Example1231313s")
        mainFrame.setSize(400, 400)
        mainFrame.layout = GridLayout(3, 1)
        mainFrame.setLocation(800, 500)
        headerLabel = JLabel("", JLabel.CENTER)
        statusLabel = JLabel("", JLabel.CENTER)
        statusLabel.setSize(350, 100)
        mainFrame.addWindowListener(object : WindowAdapter() {
            override fun windowClosing(windowEvent: WindowEvent) {
                exitProcess(0)
            }
        })
        controlPanel = JPanel()
        controlPanel.layout = FlowLayout()
        mainFrame.add(headerLabel)
        mainFrame.add(controlPanel)
        mainFrame.add(statusLabel)
        mainFrame.isVisible = true

        // 调用 fetchAndDisplayImages() 函数获取并显示图片
        fetchAndDisplayImages(mainFrame, "https://www.baidu.com");

        Thread {
            while (true) {
                // System.setOut(PrintStream(OutputStreamWriter(System.out, StandardCharsets.UTF_8)));
                System.out.println("中国等待123123")
                sleep(1000)
            }
        }.start()
    }

    private fun showEventDemo() {
        headerLabel.text = "Control in action: Button"
        val okButton = JButton("OK")
        val submitButton = JButton("Submit")
        val cancelButton = JButton("Cancel")
        okButton.actionCommand = "OK"
        submitButton.actionCommand = "Submit"
        cancelButton.actionCommand = "Cancel"
        okButton.addActionListener(ButtonClickListener())
        submitButton.addActionListener(ButtonClickListener())
        cancelButton.addActionListener(ButtonClickListener())
        controlPanel.add(okButton)
        controlPanel.add(submitButton)
        controlPanel.add(cancelButton)
        mainFrame.isVisible = true
    }

    private inner class ButtonClickListener : ActionListener {
        override fun actionPerformed(e: ActionEvent) {
            when (e.actionCommand) {
                "OK" -> statusLabel.text = "Ok Button clicked."
                "Submit" -> statusLabel.text = "Submit Button clicked."
                else -> statusLabel.text = "Cancel Button clicked."
            }
        }
    }

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {

            //  Test()
            //      GameTest()
            //  CommandLine()
            val swingControlDemo = SwingControlDemo()
            swingControlDemo.showEventDemo()
        }
    }

    init {
        prepareGUI()
    }
}